package com.zhaopin.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zhaopin.bean.JsonBean;
import com.zhaopin.bean.YamlBean;
import org.apache.commons.io.IOUtils;
import org.junit.Before;
import org.junit.Test;
import org.yaml.snakeyaml.Yaml;

import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Properties;

/**
 * @author Administrator
 * @create 2020-05-18 11:17
 */
public class JsonPropertiesUtils {


    public static Properties properties = new Properties();

    public static YamlBean yamlBean = new YamlBean();

    public static JsonBean jsonBean = new JsonBean();

    public static JSONObject jsonObject = new JSONObject();

    /**
     *  json 转 properties
     */
    @Test
    public void testJson2Pro() {
        // 第一步转 map
        Map map  = jsonObject.toJavaObject(Map.class);
        // 第二步 转Properties
        Properties properties = new Properties();
        properties.putAll(map);
        System.out.println(properties.values());
    }

    /**
     * properties 转 json
     */
    @Test
    public void testPro2Json(){
        System.out.println(JSON.toJSONString(properties));
    }



    /**
     * 初始化三个不同的文件
     */
    @Before
    public void init() {

        InputStream in = JsonPropertiesUtils.class.getClassLoader().getResourceAsStream("configs.properties");
        InputStream yamlIn = JsonPropertiesUtils.class.getClassLoader().getResourceAsStream("configs.yml");
        InputStream jsonIn = JsonPropertiesUtils.class.getClassLoader().getResourceAsStream("configs.json");
        try {
            //初始化 properties
            properties.load(in);
            //初始化 yaml
            Yaml yaml = new Yaml();
            yamlBean = yaml.loadAs(yamlIn, YamlBean.class);
            //初始化jsonObject
            String jsonStr = IOUtils.toString(jsonIn,"UTF-8");
            if(JSON.isValid(jsonStr)){
                jsonObject = JSON.parseObject(jsonStr);
            }
            jsonBean = JSON.parseObject(jsonStr,JsonBean.class);
            System.out.println("init configs.properties: " + properties.values());
            System.out.println("init configs.yml: " + yamlBean.toString());
            System.out.println("init configs.json: " + jsonBean.toString());
            System.out.println("init configs.json: " + jsonObject.toJSONString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
